const orderAddressModel = require('../models/order_address');

// 保存订单地址信息
exports.saveOrderAddress = async (req, res) => {
  try {
    // 获取请求体中的数据
    const { 
      order_id, 
      consignee_name, 
      phone_number, 
      province = '', 
      city = '', 
      district = '', 
      detail_address, 
      remarks = '', 
      delivery_time = '' 
    } = req.body;

    // 基本参数验证
    if (!order_id || !consignee_name || !phone_number || !detail_address) {
      return res.status(400).json({
        success: false,
        message: '缺少必要的地址参数: order_id, consignee_name, phone_number, detail_address'
      });
    }

    // 创建地址数据对象
    const addressData = {
      order_id: parseInt(order_id),
      consignee_name,
      phone_number,
      province,
      city,
      district,
      detail_address,
      remarks,
      delivery_time
    };

    // 调用模型保存地址信息
    const savedAddress = await orderAddressModel.saveOrderAddress(addressData);

    // 返回成功响应
    res.json({
      success: true,
      data: savedAddress,
      message: '保存订单地址成功'
    });
  } catch (error) {
    console.error('保存订单地址失败:', error);
    res.status(500).json({
      success: false,
      message: '保存订单地址失败，请稍后重试'
    });
  }
};

// 获取全部订单地址信息
exports.getAllOrderAddresses = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search = '' } = req.query;
    
    const orderAddresses = await orderAddressModel.getAllOrderAddresses(page, pageSize, search);
    
    res.json({
      success: true,
      data: orderAddresses,
      message: '获取全部订单地址成功'
    });
  } catch (error) {
    console.error('获取全部订单地址失败:', error);
    res.status(500).json({
      success: false,
      message: '获取全部订单地址失败，请稍后重试'
    });
  }
};

// 获取订单地址信息
exports.getOrderAddress = async (req, res) => {
  try {
    const { order_id } = req.query;

    if (!order_id) {
      return res.status(400).json({
        success: false,
        message: '缺少订单ID参数'
      });
    }

    const address = await orderAddressModel.getAddressByOrderId(parseInt(order_id));

    if (!address) {
      return res.status(404).json({
        success: false,
        message: '未找到该订单的地址信息',
        data: null
      });
    }

    res.json({
      success: true,
      data: address,
      message: '获取订单地址成功'
    });
  } catch (error) {
    console.error('获取订单地址失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单地址失败，请稍后重试'
    });
  }
};

// 更新订单地址信息 (与保存功能类似，可以复用saveOrderAddress方法)
exports.updateOrderAddress = async (req, res) => {
  try {
    const { 
      order_id, 
      consignee_name, 
      phone_number, 
      province = '', 
      city = '', 
      district = '', 
      detail_address, 
      remarks = '', 
      delivery_time = '' 
    } = req.body;

    if (!order_id) {
      return res.status(400).json({
        success: false,
        message: '缺少订单ID参数'
      });
    }

    // 检查地址是否存在
    const existingAddress = await orderAddressModel.getAddressByOrderId(parseInt(order_id));
    if (!existingAddress) {
      return res.status(404).json({
        success: false,
        message: '未找到该订单的地址信息'
      });
    }

    // 创建更新数据对象（保留原有值，只更新提供的值）
    const updateData = {
      order_id: parseInt(order_id),
      consignee_name: consignee_name || existingAddress.consignee_name,
      phone_number: phone_number || existingAddress.phone_number,
      province: province !== undefined ? province : existingAddress.province,
      city: city !== undefined ? city : existingAddress.city,
      district: district !== undefined ? district : existingAddress.district,
      detail_address: detail_address || existingAddress.detail_address,
      remarks: remarks !== undefined ? remarks : existingAddress.remarks,
      delivery_time: delivery_time !== undefined ? delivery_time : existingAddress.delivery_time
    };

    const updatedAddress = await orderAddressModel.saveOrderAddress(updateData);

    res.json({
      success: true,
      data: updatedAddress,
      message: '更新订单地址成功'
    });
  } catch (error) {
    console.error('更新订单地址失败:', error);
    res.status(500).json({
      success: false,
      message: '更新订单地址失败，请稍后重试'
    });
  }
};

// 根据条件搜索订单地址信息
exports.searchOrderAddresses = async (req, res) => {
  try {
    // 从查询参数中获取搜索条件和分页信息
    const {
      order_id,
      consignee_name,
      phone_number,
      province,
      city,
      district,
      detail_address,
      page = 1,
      pageSize = 10
    } = req.query;

    // 构建搜索条件对象，只包含非空的条件
    const searchConditions = {};
    if (order_id) searchConditions.order_id = parseInt(order_id);
    if (consignee_name) searchConditions.consignee_name = consignee_name;
    if (phone_number) searchConditions.phone_number = phone_number;
    if (province) searchConditions.province = province;
    if (city) searchConditions.city = city;
    if (district) searchConditions.district = district;
    if (detail_address) searchConditions.detail_address = detail_address;

    // 调用模型层的搜索方法
    const searchResult = await orderAddressModel.searchOrderAddresses(searchConditions, page, pageSize);

    res.json({
      success: true,
      data: searchResult,
      message: '搜索订单地址成功'
    });
  } catch (error) {
    console.error('搜索订单地址失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索订单地址失败，请稍后重试'
    });
  }
};

// 删除订单地址信息
exports.deleteOrderAddress = async (req, res) => {
  try {
    // 同时支持从请求体和URL查询参数中获取order_id
    const order_id = req.body.order_id || req.query.order_id;

    if (!order_id) {
      return res.status(400).json({
        success: false,
        message: '缺少订单ID参数'
      });
    }

    // 检查地址是否存在
    const existingAddress = await orderAddressModel.getAddressByOrderId(parseInt(order_id));
    if (!existingAddress) {
      return res.status(404).json({
        success: false,
        message: '未找到该订单的地址信息'
      });
    }

    await orderAddressModel.deleteOrderAddress(parseInt(order_id));

    res.json({
      success: true,
      message: '删除订单地址成功'
    });
  } catch (error) {
    console.error('删除订单地址失败:', error);
    res.status(500).json({
      success: false,
      message: '删除订单地址失败，请稍后重试'
    });
  }
};